package com.runningfox.logic;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import android.content.Context;
import android.util.Log;

import com.runningfox.humor.ProcessCallback;
import com.runningfox.model.Setting;

public class StreamToolBox {

	public static InputStream loadStreamFromGzipFile(String fileName) {
		File f = new File(fileName);
		if (!f.exists())
			return null;
		try {
			InputStream is = new FileInputStream(f);
			return new GZIPInputStream(is);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static InputStream loadStreamFromFile(String fileName) {
		File f = new File(fileName);
		if (!f.exists())
			return null;
		try {
			return new FileInputStream(f);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static InputStream loadStreamFromURL(String requestUrl,
			ProcessCallback callback) {
		Log.v("humordeug", requestUrl);
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("Accept-encoding", "gzip");
			int resCode = conn.getResponseCode();
			if (resCode == 200) {

				conn.connect();
				InputStream is = conn.getInputStream();
				int bytes =is.available();
				Log.v("debug", "the data size is "+bytes +"b");
				if (callback != null) {
					callback.onHttp200();
				}
				return is;
			} else if (resCode == 404 && callback != null) {
				callback.onHttp404();
			} else if (resCode >= 500 && callback != null) {
				callback.onHttp500();
			}

			// try {
			// Log.v("string", StreamToolBox.loadStringFromStream(is));
			// } catch (IOException e1) {
			// // TODO Auto-generated catch block
			// e1.printStackTrace();
			// }
			// is =new GZIPInputStream(is);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			callback.onHttpFaild();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			callback.onHttpFaild();
		} catch (Exception e) {
			e.printStackTrace();
			callback.onHttpFaild();
		}
		return null;
	}

	public static String loadStringFromFile(String filePathName) throws FileNotFoundException, IOException{
		File f=new File(filePathName);
		if(f.exists()){
			return loadStringFromStream(new FileInputStream(filePathName));
		}else {
			return null;
		}
	}

	public static String loadStringFromGZIPStream(InputStream in)
			throws IOException {
		return in != null ? loadStringFromStream(new GZIPInputStream(in))
				: null;
	}

	public static String loadStringFromStream(InputStream in)
			throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
		copyStream(in, baos);
		baos.close();
		return baos.toString("UTF-8");
	}

	public static void saveGZipStreamToFile(InputStream in, String fileNamePath)
			throws IOException {
		saveStreamToFile(new GZIPInputStream(in), fileNamePath);
	}

	public static String extractGZipStreamToString(InputStream in)
			throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		copyStream(new GZIPInputStream(in), baos);
		return baos.toString("UTF-8");
	}

	public static void saveStringToFile(String str, String fileNamePath)
			throws IOException {
		saveStreamToFile(new ByteArrayInputStream(str.getBytes("UTF-8")),
				fileNamePath);
	}

	/**
	 * 保存流入文件， 返回文件名称
	 * 保存到sd卡
	 * @param in
	 * @param fileNamePath
	 * @return
	 * @throws IOException
	 */
	
	static String SDDIR = "//sdcard/humor/";
	public static String saveStreamToFileSD(InputStream in, String fileNamePath)
			throws IOException {
		if (in == null) {
			return null;
		}
		File f = new File(fileNamePath);
		if (f.exists()) {
			f.delete();
		} else {
			File dirFile = new File(SDDIR);
			if (!dirFile.exists()) {
				dirFile.mkdir();
			}
			f.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(f);
		copyStream(in, fos);
		fos.close();
		return fileNamePath;
	}

	public static String saveStreamToFile(InputStream in, String fileNamePath)
			throws IOException {
		if (in == null) {
			return null;
		}
		File f = new File(fileNamePath);
		if (f.exists()) {
			f.delete();
		} else {
			f.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(f);
		copyStream(in, fos);
		fos.close();
		return fileNamePath;
	}
	
	public static void copyStream(InputStream in, OutputStream out)
			throws IOException {
		BufferedInputStream bin = new BufferedInputStream(in);
		BufferedOutputStream bout = new BufferedOutputStream(out);

		byte[] buffer = new byte[4096];

		while (true) {
			int doneLength = bin.read(buffer);
			if (doneLength == -1)
				break;
			bout.write(buffer, 0, doneLength);
		}
		bout.flush();
	}

	public static void dumpAssetToDataFile(Context ctx, String assetName,
			String storePath) {
		// DebugToolBox.Log("Dumping Asset " + assetName + " to path " +
		// storePath);
		try {
			InputStream is = ctx.getAssets().open(assetName);
			StreamToolBox.saveStreamToFile(is, storePath + File.separator
					+ assetName);
		} catch (IOException e) {
			// DebugToolBox.Log("Failed to dump asset " + assetName +
			// " to path " + storePath + ". Reason: " + e.getMessage());
		}
	}
}
